package com.ruoyi.binding.controller;

import java.security.Security;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.binding.service.impl.DispatchTaskService;
import com.ruoyi.common.utils.SecurityUtils;
import org.quartz.SchedulerException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.binding.domain.MhUserGameDispatchConfig;
import com.ruoyi.binding.service.IMhUserGameDispatchConfigService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 自动派单Controller
 *
 * @author Ekko
 * @date 2025-06-26
 */
@RestController
@RequestMapping("/order/auto")
public class MhUserGameDispatchConfigController extends BaseController {
    @Autowired
    private IMhUserGameDispatchConfigService mhUserGameDispatchConfigService;

    @Autowired
    private DispatchTaskService dispatchTaskService;

    /**
     * 查询自动派单列表
     */
    @PreAuthorize("@ss.hasPermi('order:auto:list')")
    @GetMapping("/list")
    public TableDataInfo list(MhUserGameDispatchConfig mhUserGameDispatchConfig) {
        startPage();
        List<MhUserGameDispatchConfig> list = mhUserGameDispatchConfigService.selectMhUserGameDispatchConfigList(mhUserGameDispatchConfig);
        return getDataTable(list);
    }

    /**
     * 获取当前用户可操作游戏
     */
    @GetMapping("/getUserGameList")
    public AjaxResult getUserGameList() {
        return success(mhUserGameDispatchConfigService.getUserGameList());
    }

    /**
     * 导出自动派单列表
     */
    @PreAuthorize("@ss.hasPermi('order:auto:export')")
    @Log(title = "自动派单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MhUserGameDispatchConfig mhUserGameDispatchConfig) {
        List<MhUserGameDispatchConfig> list = mhUserGameDispatchConfigService.selectMhUserGameDispatchConfigList(mhUserGameDispatchConfig);
        ExcelUtil<MhUserGameDispatchConfig> util = new ExcelUtil<MhUserGameDispatchConfig>(MhUserGameDispatchConfig.class);
        util.exportExcel(response, list, "自动派单数据");
    }

    /**
     * 获取自动派单详细信息
     */
    @PreAuthorize("@ss.hasPermi('order:auto:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(mhUserGameDispatchConfigService.selectMhUserGameDispatchConfigById(id));
    }


    /**
     * 构建任务名称
     * 该方法根据配置信息构建一个唯一的任务名称，包含时间戳、用户ID和游戏名称。
     * 如果用户ID或游戏名称为空，则分别用"unknownUser"和"unknownGame"代替。
     *
     * @param config 任务配置信息，包含用户ID和游戏名称等参数
     * @return 返回格式为"dispatch_时间戳_uid用户ID_游戏名称"的字符串
     */
    private Long buildTaskName(MhUserGameDispatchConfig config) {
        long timestamp = System.currentTimeMillis();
//        获取当前用户id
        long userId = SecurityUtils.getUserId();
//      直接返回编号+时间戳
        return timestamp + userId;
    }

    /**
     * 新增自动派单
     *
     * @param mhUserGameDispatchConfig 自动派单配置实体
     * @return 操作结果
     */
    @PreAuthorize("@ss.hasPermi('order:auto:add')")
    @Log(title = "自动派单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MhUserGameDispatchConfig mhUserGameDispatchConfig) {
        if (getBotUrls() == null || getBotUrls().isEmpty()) {
            return error("请前往个人信息页配置机器人Webhook地址");
        }
        Date now = new Date();
        mhUserGameDispatchConfig.setNextTime(now);
        mhUserGameDispatchConfig.setTaskId(buildTaskName(mhUserGameDispatchConfig));
        mhUserGameDispatchConfig.setRemark("用户[" + SecurityUtils.getUsername() + "]创建任务");
        mhUserGameDispatchConfig.setWebhookUrls(getBotUrls().toString());
        if (mhUserGameDispatchConfigService.insertMhUserGameDispatchConfig(mhUserGameDispatchConfig) > 0) {
            return success("任务启动成功,稍后将开始派单");
        }
        return error("任务启动失败");
    }

    /**
     * 修改自动派单
     *
     * @param mhUserGameDispatchConfig 自动派单配置实体
     * @return 操作结果
     */
    @PreAuthorize("@ss.hasPermi('order:auto:edit')")
    @Log(title = "自动派单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MhUserGameDispatchConfig mhUserGameDispatchConfig) {
        if (mhUserGameDispatchConfigService.updateMhUserGameDispatchConfig(mhUserGameDispatchConfig) > 0) {
            return success("任务修改成功");
        }
        return error("任务修改失败");
    }

    /**
     * 删除自动派单
     */
    @PreAuthorize("@ss.hasPermi('order:auto:remove')")
    @Log(title = "自动派单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
       if (mhUserGameDispatchConfigService.deleteMhUserGameDispatchConfigByIds(ids) > 0) {
            return success("删除成功");
        }
        return error("删除失败");
    }
}
